package br.com.jvet.converter;

import java.io.Serializable;

import java.text.NumberFormat;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("doubleConverter")
public class DoubleConvert implements Converter, Serializable {
	private static final long serialVersionUID = -3901325601865698703L;

	private int decimais = 2;

	private static final Integer DEFAULT_DECIMAIS = 2;

	public Object getAsObject(final FacesContext context,
			final UIComponent component, final String value) {
		try {
			final NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(decimais);
			return nf.parse(value).doubleValue();
		} catch (final Exception e) {
			return 0.0D;
		}
	}

	public String getAsString(final FacesContext context,
			final UIComponent component, Object value) {

		if ((value == null) || (value.toString().trim().equals(""))) {
			value = 0.0D;
		}

		this.decimais = getDecimais(component);

		final NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(this.decimais);

		return nf.format(Double.valueOf(value.toString()));
	}

	private int getDecimais(UIComponent component) {
		Object att = component.getAttributes().get("decimais");

		if (att == null)
			return DEFAULT_DECIMAIS;
		else
			return Integer.parseInt((String) component.getAttributes().get(
					"decimais"));
	}

}
